package com.linewow.xhyy.nihaonew.fragment;

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.hrxb.DemoHelper;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.adapter.FindTopicAdapter;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseFragment;
import com.linewow.xhyy.nihaonew.db.NiHaoHelper;
import com.linewow.xhyy.nihaonew.entity.NiHaoEntity;
import com.linewow.xhyy.nihaonew.entity.image.ImagesInfo;
import com.linewow.xhyy.nihaonew.entity.topic.FindTopicInfo;
import com.linewow.xhyy.nihaonew.entity.user.Uinfo;
import com.linewow.xhyy.nihaonew.event.MessageEvent;
import com.linewow.xhyy.nihaonew.model.HttpModel;
import com.linewow.xhyy.nihaonew.util.NewsCallback;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by LXR on 2016/8/31.
 * 用户搜索
 */
public class SearchResultFragment extends BaseFragment {
    @Bind(R.id.search_result_lv)
    ListView searchResultLv;
    @Bind(R.id.search_result_mask)
    RelativeLayout searchResultMask;
    private String TAG = "SearchResultFragment";
    private Type findTopicType;
    private List<FindTopicInfo<ImagesInfo, Uinfo>> findTopicInfos;
    private Gson gson;
    private FindTopicAdapter findTopicAdapter;
    private NiHaoHelper niHaoHelper;


    @Override
    public View initView() {
        View view = View.inflate(getActivity(), R.layout.fragment_search_result, null);
        EventBus.getDefault().register(SearchResultFragment.this);
        ButterKnife.bind(this, view);
        searchResultMask.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                hideSoftKeyboard();
                return false;
            }
        });

        return view;
    }

    @Override
    public void initList() {
        super.initList();
    }

    @Override
    public void initData() {
        super.initData();
        findTopicType = new TypeToken<List<FindTopicInfo<ImagesInfo, Uinfo>>>() {
        }.getType();
        gson = new Gson();
        findTopicInfos = new ArrayList<>();
        findTopicAdapter = new FindTopicAdapter(findTopicInfos, SearchResultFragment.this.getActivity());
        searchResultLv.setAdapter(findTopicAdapter);
        niHaoHelper = NiHaoHelper.getInstance();

    }

    @Subscriber(tag = "Search", mode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        requestInfo(messageEvent);
    }

    @Subscriber(tag = "FindTopicAdapter", mode = ThreadMode.MAIN)
    public void onAttentionChange(MessageEvent messageEvent) {
        Log.e(TAG, "被点击了");
        final int index = messageEvent.getIndex();
        final FindTopicInfo<ImagesInfo, Uinfo> findTopicInfo = findTopicInfos.get(index);
        boolean isFllow = findTopicInfo.isfollow;
        if (!NiHaoApp.flag) {
            DemoHelper.getInstance().onConnectionConflict();
            return;
        }
        if (isFllow) {
            OkHttpUtils.get()
                    .url(HttpModel.USERUFOLLOW)
                    .addParams("touid", findTopicInfo.uid)
                    .addParams("token", NiHaoApp.token)
                    .build()
                    .execute(new NewsCallback<NiHaoEntity>(NiHaoEntity.class) {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e(TAG, "网络请求失败" + e.getMessage());
                        }

                        @Override
                        public void onResponse(NiHaoEntity response, int id) {
                            Log.e(TAG, "取消结果返回" + response);
                            if (response.status) {
                                findTopicInfo.setIsfollow(false);
                                Log.e(TAG, "部分更新了" + findTopicInfo.isfollow);
                                updateView(index);
                            }
                        }
                    });
        } else {
            OkHttpUtils.get()
                    .url(HttpModel.USERFOLLOW)
                    .addParams("touid", findTopicInfo.uid)
                    .addParams("token", NiHaoApp.token)
                    .build()
                    .execute(new NewsCallback<NiHaoEntity>(NiHaoEntity.class) {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.e(TAG, "网络请求失败" + e.getMessage());
                        }

                        @Override
                        public void onResponse(NiHaoEntity response, int id) {
                            Log.e(TAG, "关注结果返回" + response);
                            if (response.status) {
                                findTopicInfo.setIsfollow(true);
                                updateView(index);
                                String content = getActivity().getResources().getString(R.string.message_attention_content);
                                niHaoHelper.requestAttention(findTopicInfo.uid, content, findTopicInfo.uid);//这里传什么rid
                            }
                        }
                    });
        }
    }


    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(SearchResultFragment.this);
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    private void requestInfo(MessageEvent messageEvent) {
        Log.e(TAG, "搜索的词" + messageEvent.getMessage());
        showProgressBar();
        OkHttpUtils.post().url(HttpModel.SEARCHUSER)
                .addParams("q", messageEvent.getMessage())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        dismissProgressBar();
                        Log.e(TAG, "请求错误了");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        dismissProgressBar();
                        findTopicInfos.clear();
                        Log.e(TAG, "信息" + response);
                        List<FindTopicInfo<ImagesInfo, Uinfo>> list = gson.fromJson(response, findTopicType);
                        findTopicInfos.addAll(list);
                        findTopicAdapter.notifyDataSetChanged();
                        if (findTopicInfos.size() == 0) {
                            showNoData();
                        } else {
                            dismissNoData();
                        }
                    }
                });
    }

    private void updateView(int index) {
        int visiblePosition = searchResultLv.getFirstVisiblePosition();
        if (index - visiblePosition >= 0) {
            //得到要更新的item的view
            View view = searchResultLv.getChildAt(index - visiblePosition);
            //调用adapter更新界面
            findTopicAdapter.updateView(view, index);
        }
    }

}
